package org.Image.management.SpringDataService.Service.Sys_User.dataService;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.Image.management.SpringDataService.Pojo.Exception.BusinessException;
import org.Image.management.SpringDataService.Pojo.Exception.StatusCode;
import org.Image.management.SpringDataService.Service.Sys_User.Pojo.mapper.User;
import org.Image.management.SpringDataService.Service.Sys_User.dataService.impl.UserDataServiceInterface;
import org.Image.management.SpringDataService.Service.Sys_User.mapper.UserMapper;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service
@RequiredArgsConstructor
@Slf4j
public class UserDataService extends ServiceImpl<UserMapper, User> implements UserDataServiceInterface {

    private final UserMapper userMapper;

    @Override
    public User addUser(User user) {
        // 判断用户名是否存在
        if (isUsernameFind(user.getUserName())) {
            throw new BusinessException(StatusCode.BAD_REQUEST, "用户名已存在,请重新输入!");
        }

        if (!this.save(user)) {
            throw new BusinessException(StatusCode.ERROR_CODE, "新增用户失败,请联系客服!");
        }

        return user;
    }


    @Override
    public User updateUser(User user) {

        if (userMapper.updateById(user) <= 0) {
            throw new BusinessException(StatusCode.ERROR_CODE, "更新用户失败,请联系客服!");
        }
        return user;
    }

    @Override
    public Boolean isUsernameFind(String username) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>(User.class).eq(User::getUserName, username);
        return userMapper.exists(queryWrapper);
    }

    @Override
    public Boolean isUserPasswordFind(Long id, String password) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>(User.class).allEq(Map.of(User::getId, id, User::getPassword, password));
        return userMapper.exists(queryWrapper);
    }

    @Override
    public User login(String username, String password,boolean isUserDelete) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>(User.class).allEq( Map.of(
                User::getUserName, username,
                User::getPassword, password,
                User::getUserDelete, isUserDelete
        ));

        User user = userMapper.selectOne(queryWrapper);

        if (user == null) {
            throw new BusinessException(StatusCode.BAD_REQUEST, "用户名或密码错误");
        }

        return user;
    }
}
